package cn.leedsoft.luma.plugins.shiro;

import cn.leedsoft.luma.plugins.memcached.MemcachedUtil;
import net.spy.memcached.MemcachedClient;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * 用memcached，实现SessionDAO
 */
@Component
public class MemcacheSessionDAO extends AbstractSessionDAO {
    @Value("#{confProperty['session.prefix']}")
    private String sessionPrefix;//sessionId前缀

    @Autowired
    private MemcachedUtil memcachedUtil;

    public void update(Session session) throws UnknownSessionException {
        String key = sessionPrefix + session.getId();
        memcachedUtil.safeSet(key, Long.valueOf(TimeUnit.DAYS.toSeconds(1)).intValue(),session);
    }

    public void delete(Session session) {
        String key = sessionPrefix + session.getId();
        memcachedUtil.safeDelete(key);
    }

    //TODO 获取所有活跃session的方法
    public Collection<Session> getActiveSessions() {
        return null;
    }

    protected Serializable doCreate(Session session) {
        String key = sessionPrefix + session.getId();
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        memcachedUtil.safeSet(key,Long.valueOf(TimeUnit.DAYS.toSeconds(1)).intValue(),session);
        return sessionId;
    }
    protected Session doReadSession(Serializable sessionId) {
        String key = sessionPrefix + sessionId;
        return memcachedUtil.get(key);
    }
}
